package tcu.iot.gasmanage.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tcu.iot.gasmanage.common.utils.JwtUtils;
import tcu.iot.gasmanage.common.Result;
import tcu.iot.gasmanage.entity.Token;
import tcu.iot.gasmanage.entity.user.User;
import tcu.iot.gasmanage.mapper.TokenMapper;
import tcu.iot.gasmanage.mapper.UserMapper;

import javax.annotation.Resource;
import java.util.HashMap;

@Service
@Transactional
public class UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private TokenMapper tokenMapper;

    public Result LoginUser(User user) {

        HashMap<String, Object> hashMap = new HashMap();

        User userReturn = userMapper.LoginUser(user.getUsername(), user.getPassword());

        if (userReturn != null) {
            if (tokenMapper.getByTokenUsername(user.getUsername()) != null) {
                tokenMapper.DeleteToken(user.getUsername());

                return Result.failed("false", 401, "您已经在别处登录，请再次登录!");
            } else {
                Token token = JwtUtils.generateToken(userReturn);

                tokenMapper.InsertToken(token);

                hashMap.put("token", token.getToken());

                return Result.ok("true", 200, "成功", hashMap);
            }
        } else
            return Result.failed("false", 401, "用户名或密码错误，请重新输入！");
    }

    public Result LoginOut(String token) {
        HashMap<String, Object> hashMap = JwtUtils.validateToken(token);

        if (tokenMapper.DeleteToken(hashMap.get("username").toString()))
            return Result.ok("true", 200, "退出成功", "退出成功");
        else
            return Result.failed("false", 400, "退出失败");
    }


    public boolean FindPassword(String username, String password) {
        return userMapper.FindPassword(username, password);
    }

    public Result LoginInfo(String token) {
        HashMap<String, Object> hashMap = JwtUtils.validateToken(token);

        return Result.ok("true", 200, "成功", hashMap);

    }

    public Result UpdatePassword(String username, String oldPassword, String newPassword) {
        if (userMapper.FindPassword(username, oldPassword)) {
            userMapper.UpdatePassword(username, newPassword);
            return Result.ok("true", 200, "成功", "密码修改成功！");
        } else {
            return Result.failed("false", 401, "密码修改失败，请稍后再试！");
        }
    }
}
